package study.demo.MES;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class Demo1 {
    public static void main(String[] args) {
        // 用户输入的数据
        ProductionParam productionParam = new ProductionParam();
        productionParam.setFormItemType("input");
        productionParam.setParamValue("无");
        productionParam.setOptionItems("[{\"label\":\"是\",\"value\":\"1\"},{\"label\":\"否\",\"value\":\"2\"}]");
        productionParam.setFieldDescription("1.2.4.华通氏胶分离洗涤离心，离心参数min");
        // 151:大于等于，152: 小于等于，153:小于，154:大于，155:等于，156:不等于，157:包含，158:不包含，159:是，160:不是
        Boolean result = handle(152, productionParam, "5");
        System.out.println(result); // 输出:没有定义
    }

    private static Boolean handle(Integer operationalSymbol, ProductionParam productionParam, String compareValue) {
        Object paramValue = null;
        String formItemType = productionParam.getFormItemType();
        String paramValueObj = productionParam.getParamValue().toString();
        String fieldDescription = productionParam.getFieldDescription();
        try {
            switch (formItemType) {
                case "date":
                    // 转换为 LocalDate
                    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    paramValue = LocalDate.parse(paramValueObj, dateFormatter);
                    break;
                case "time":
                    // 转换为 LocalDate
                    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
                    paramValue = LocalTime.parse(paramValueObj, timeFormatter);
                    break;
                case "checkbox":
                    Map<Object, Object> resultMap = getObjectObjectMap(productionParam);
                    List<Object> valueList = null;
                    if (paramValueObj.startsWith("[") && paramValueObj.endsWith("]")) {
                        JSONArray jsonArray = new JSONArray(paramValueObj);
                        List<Object> keyList = new ArrayList<>(jsonArray);
                        valueList = new ArrayList<>();
                        for (Object o : keyList) {
                            valueList.add(resultMap.get(o));
                        }
                    }

                    paramValue = valueList;
                    break;
                case "radio":
                case "select":
                    // 需要根据key找value
                    Map<Object, Object> resultMap2 = getObjectObjectMap(productionParam);
                    paramValue = resultMap2.get(paramValueObj);
                    break;
                case "switch":
                case "input":
                case "static-input":
                case "textarea":
                case "number":
                case "rate":
                    // 不需要根据key找value
                    paramValue = paramValueObj;
            }

            log.info("operationalSymbol:{},paramValueList:{},compareValue:{}", operationalSymbol, productionParam, compareValue);

            log.info("paramValue:{}", paramValue);
            switch (operationalSymbol) {
                case 151:
                    // 大于等于
                    if (formItemType.equals("date-range") || formItemType.equals("time-range")) {
                        return false;
                    } else {
                        return getGeBoolean(compareValue, formItemType, paramValue);
                    }
                case 152:
                    // 小于等于
                    if (formItemType.equals("date-range") || formItemType.equals("time-range")) {
                        return false;
                    } else {
                        return getLeBoolean(compareValue, formItemType, paramValue);
                    }
                case 153:
                    // 小于
                    if (formItemType.equals("date-range") || formItemType.equals("time-range")) {
                        return false;
                    } else {
                        return getLtBoolean(compareValue, formItemType, paramValue);
                    }
                case 154:
                    // 大于
                    if (formItemType.equals("date-range") || formItemType.equals("time-range")) {
                        return false;
                    } else {
                        return getGtBoolean(compareValue, formItemType, paramValue);
                    }
                case 155:
                    // 等于
                    if (formItemType.equals("date-range") || formItemType.equals("time-range")) {
                        return false;
                    } else {
                        return getEqualsBoolean(compareValue, formItemType, paramValue);
                    }
                case 156:
                    // 不等于
                    if (formItemType.equals("date-range") || formItemType.equals("time-range")) {
                        return false;
                    } else {
                        return !getEqualsBoolean(compareValue, formItemType, paramValue);
                    }
                case 157:
                    // 包含
                    if (formItemType.equals("date") || formItemType.equals("time")) {
                        return false;
                    } else {
                        return getContainBoolean(compareValue, formItemType, paramValue);
                    }
                case 158:
                    // 不包含
                    if (formItemType.equals("date") || formItemType.equals("time")) {
                        return false;
                    } else {
                        return !getContainBoolean(compareValue, formItemType, paramValue);
                    }
                case 159:
                    // 是
                    if (formItemType.equals("date-range") || formItemType.equals("time-range")) {
                        return false;
                    } else {
                        return getEqualsBoolean(compareValue, formItemType, paramValue);
                    }
                case 160:
                    // 不是
                    if (formItemType.equals("date-range") || formItemType.equals("time-range")) {
                        return false;
                    } else {
                        return !getEqualsBoolean(compareValue, formItemType, paramValue);
                    }
            }
        } catch (NumberFormatException e) {
            log.error("NumberFormatException", e);
            throw new BusinessException(BusinessExceptionEnum.TASK_CONDITIONS_Contrast_TYPE_FASLE, fieldDescription + "只能输入数字");
        } catch (DateTimeParseException e) {
            log.error("DateTimeParseException", e);
            throw new BusinessException(BusinessExceptionEnum.TASK_CONDITIONS_Contrast_TYPE_FASLE, fieldDescription + "只能输入时间格式");
        }
        throw new BusinessException(BusinessExceptionEnum.TASK_CONDITIONS_Contrast_TYPE_NULL);
    }

    private static Boolean getGeBoolean(String compareValue, String formItemType, Object paramValue) {
        return getGtBoolean(compareValue, formItemType, paramValue) || getEqualsBoolean(compareValue, formItemType, paramValue);
    }

    private static Boolean getLeBoolean(String compareValue, String formItemType, Object paramValue) {
        return getLtBoolean(compareValue, formItemType, paramValue) || getEqualsBoolean(compareValue, formItemType, paramValue);
    }

    private static Boolean getGtBoolean(String compareValue, String formItemType, Object paramValue) {
        switch (formItemType) {
            case "checkbox":
                List<String> paramValueList = (List<String>) paramValue;
                assert paramValueList != null;
                for (String param : paramValueList) {
                    if (Integer.parseInt(param) > Integer.parseInt(compareValue)) {
                        return true;
                    }
                }
                return false;
            case "radio":
            case "select":
            case "input":
            case "static-input":
            case "textarea":
            case "number":
            case "rate":
            case "switch":
                return new BigDecimal(paramValue.toString()).compareTo(new BigDecimal(compareValue)) > 0;


            case "date":
                // 转换为 LocalDate
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate compareValueDate = LocalDate.parse(compareValue, dateFormatter);
                LocalDate paramValueDate = (LocalDate) paramValue;
                return ContrastUtil.dateGtBoolean(paramValueDate, compareValueDate);

            case "time":
                // 转换为 LocalTime
                DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
                LocalTime compareValueTime = LocalTime.parse(compareValue, timeFormatter);
                LocalTime paramValueTime = (LocalTime) paramValue;
                return ContrastUtil.timeGtBoolean(paramValueTime, compareValueTime);
        }

        throw new BusinessException(BusinessExceptionEnum.TASK_CONDITIONS_Contrast_TYPE_FASLE);
    }

    private static Boolean getLtBoolean(String compareValue, String formItemType, Object paramValue) {
        switch (formItemType) {
            case "checkbox":
                List<String> paramValueList = (List<String>) paramValue;
                assert paramValueList != null;
                for (String param : paramValueList) {
                    if (Integer.parseInt(param) < Integer.parseInt(compareValue)) {
                        return true;
                    }
                }
                return false;
            case "radio":
            case "select":
            case "input":
            case "static-input":
            case "textarea":
            case "number":
            case "rate":
            case "switch":
                return new BigDecimal(paramValue.toString()).compareTo(new BigDecimal(compareValue)) < 0;

            case "date":
                // 转换为 LocalDate
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate compareValueDate = LocalDate.parse(compareValue, dateFormatter);
                LocalDate paramValueDate = (LocalDate) paramValue;
                return ContrastUtil.dateLtBoolean(paramValueDate, compareValueDate);

            case "time":
                // 转换为 LocalTime
                DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
                LocalTime compareValueTime = LocalTime.parse(compareValue, timeFormatter);
                LocalTime paramValueTime = (LocalTime) paramValue;
                return ContrastUtil.timeLtBoolean(paramValueTime, compareValueTime);


        }
        throw new BusinessException(BusinessExceptionEnum.TASK_CONDITIONS_Contrast_TYPE_FASLE);
    }

    private static Boolean getEqualsBoolean(String compareValue, String formItemType, Object paramValue) {
        switch (formItemType) {
            case "checkbox":
                List<Object> paramValueList = (List<Object>) paramValue;
                assert paramValueList != null;
                return paramValueList.contains(compareValue);
            case "radio":
            case "select":
            case "input":
            case "static-input":
            case "textarea":
            case "number":
            case "rate":
            case "switch":
                return Objects.equals(paramValue, compareValue);

            case "date":
                // 转换为 LocalDate
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate compareValueDate = LocalDate.parse(compareValue, dateFormatter);
                LocalDate paramValueDate = (LocalDate) paramValue;
                return ContrastUtil.dateEqBoolean(paramValueDate, compareValueDate);

            case "time":
                // 转换为 LocalTime
                DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
                LocalTime compareValueTime = LocalTime.parse(compareValue, timeFormatter);
                LocalTime paramValueTime = (LocalTime) paramValue;
                return ContrastUtil.timeEqBoolean(paramValueTime, compareValueTime);


        }
        throw new BusinessException(BusinessExceptionEnum.TASK_CONDITIONS_Contrast_TYPE_FASLE);
    }

    private static Boolean getContainBoolean(String compareValue, String formItemType, Object paramValue) {
        switch (formItemType) {
            case "checkbox":
                List<Object> paramValueList = (List<Object>) paramValue;
                assert paramValueList != null;
                paramValueList.contains(compareValue);
            case "radio":
            case "select":
            case "input":
            case "static-input":
            case "textarea":
            case "number":
            case "rate":
            case "switch":
                String string = paramValue.toString();
                return string.contains(compareValue);

            case "date-range":
                List<LocalDate> timeRangeList = (List<LocalDate>) paramValue;
                assert timeRangeList != null;
                // 转换为 LocalDate
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate compareValueDate = LocalDate.parse(compareValue, dateFormatter);
                return ContrastUtil.dateContainBoolean(timeRangeList.get(0), timeRangeList.get(1), compareValueDate);

            case "time-range":
                List<LocalTime> dateRangeList = (List<LocalTime>) paramValue;
                assert dateRangeList != null;
                // 转换为 LocalTime
                DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
                LocalTime compareValueTime = LocalTime.parse(compareValue, timeFormatter);
                return ContrastUtil.timeContainBoolean(dateRangeList.get(0), dateRangeList.get(1), compareValueTime);


        }
        // 其他的不通过
        throw new BusinessException(BusinessExceptionEnum.TASK_CONDITIONS_Contrast_TYPE_FASLE);
    }

    private static @NotNull Map<Object, Object> getObjectObjectMap(ProductionParam productionParam) {
        String optionItems = productionParam.getOptionItems();
        ObjectMapper mapper = new ObjectMapper();
        Map<Object, Object> resultMap = new HashMap<>();
        try {
            // 先转换为 List<Map>
            List<Map<Object, Object>> list = mapper.readValue(optionItems,
                    new TypeReference<List<Map<Object, Object>>>() {
                    });

            // 转换为 Map<String, String>，key=value, value=label
            resultMap = list.stream()
                    .collect(Collectors.toMap(
                            item -> item.get("value"),  // key = 原对象的 value 字段
                            item -> item.get("label"),  // value = 原对象的 label 字段
                            (existing, replacement) -> existing  // 处理重复key，保留第一个
                    ));

            System.out.println(resultMap);
            // 输出: {是=是, 否=否}

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

}
